<template>
  <view class="car">
    <u-cell-group>
      <u-cell-item  @click="toAddress" v-if="!checked" icon="map" :title="addressText">
        <div slot="label">
          <div class="u-box">
            <span class="name">{{ address.username  || ''}}</span>
            <span class="mobile">{{ address.phone || ''}}</span>
          </div>
        </div>
      </u-cell-item>
    </u-cell-group>
    <u-gap heigt="20"></u-gap>
    <u-empty mode="car" v-if="!buyList.length"></u-empty>
    <div class="car-list">
      <div v-for="item in buyList" :key="item.id" @click="toGoodDetail(item)">
        <u-alert-tips type="warning" :show-icon="true" :description="item.tips"></u-alert-tips>
        <div class="car-item" >
          <u-image :src="item.image" :width="160" :height="160" mode="aspectFit"></u-image>
          <div class="goods-detail">
            <div class="goods-name">{{ item.name }}</div>
            <div class="goods-price-box">
              <div class="goods-price">￥{{ item.price }}</div>
              <div class="goods-count">
                <u-icon name="minus-circle" :size="48" @click="deleteCount(item)"></u-icon>
                <span class="goods-count-value">{{ item.count }}</span>
                <u-icon name="plus-circle" :size="48" @click="addCount(item)"></u-icon>
              </div>
            </div>
            <div>
              <u-input type="textarea" border v-model="item.remark" :placeholder="item.tips"></u-input>
            </div>
          </div>
        </div>
      </div>
    </div>
    <u-gap heigt="20"></u-gap>
    <u-cell-item title="其他要求" :arrow="false">
      <div style="padding-left: 20px">
        <u-input v-model="form.remark" />
      </div>
    </u-cell-item>
    <div class="car-action">
      <div class="total">
        <span>合计：</span>
        <span class="total-value">￥{{ totalValue }}</span>
      </div>
      <div>
        <u-button style="width: 100px;margin: 0 auto;background-color: #2aac34;color: #ffffff":ripple="true" shape="circle" @click="buyAll">结算</u-button>
      </div>
    </div>
    <u-popup v-model="dateShow" mode="bottom" border-radius="14">
      <div class="date-picker-title">
        <span>选择时间</span>
        <span class="confirm-text" @click="confirmDate">确定</span>
      </div>
      <div class="date-picker-content">
        <div class="date-picker-slide">
          <div
               v-for="item in dayList"
               :key="item.day"
               @click="changeDay(item.value)"
               :class="['date-slide-item',item.value === activeDay ? 'active' :'']">
            {{ item.day }}
          </div>
        </div>
        <div class="date-time-list">
          <div
              @click="activeTime = item"
              :class="['date-time-item',item === activeTime ? 'active' :'']"
              v-for="item in timeList" :key="item">
            {{ item }}
          </div>
        </div>
      </div>
    </u-popup>
  </view>
</template>

<script>
import dayjs from 'dayjs'
export default {
  data() {
    return {
      allList: [
        {tabId: 1,name: '配送'},
      ],
      buyList: [
      ],
      address: {},
      coupon: {},
      dateShow: false,
      activeDay: dayjs().format('YYYY-MM-DD'),
      activeTime: '08:00-08:30',
      // 日期 今天 明天 后天 计算具体月日
      dayList: [
        {id: 0, day: `今天${dayjs().format('MM月DD日')}`, value: dayjs().format('YYYY-MM-DD')},
        {id: 1, day: `明天${dayjs().add(1, 'day').format('MM月DD日')}`, value: dayjs().add(1, 'day').format('YYYY-MM-DD')},
        {id: 2, day: `后天${dayjs().add(2, 'day').format('MM月DD日')}`, value: dayjs().add(2, 'day').format('YYYY-MM-DD')},
      ],
      timeList: [

      ],
      form: {
        address_id: '',
        member_id: '',
        goods: [],
        order_type: 1,
        day: '',
        time: '',
        pay_type: 'wx',
        coupon_id: '',
        remark: ''
      },
    }
  },
  computed: {
    checked() {
      return this.form.order_type === 0
    },
    addressText() {
      return this.address.id ? `${this.address.address} -${this.address.code}` : '请选择地址'
    },
    timeText() {
      if (!this.form.day || !this.form.time) {
        return '请选择时间'
      }
      // 如果是当天 显示今天 08:00-08:30
      if (this.form.day === dayjs().format('YYYY-MM-DD')) {
        return `今天 ${this.activeTime}`
      }
      return `${dayjs(this.form.day).format('MM月DD日')} ${this.form.time}`
    },
    couponText() {
      return this.coupon.id ? this.coupon.name : '请选择优惠券'
    },
    totalValue() {
      return this.buyList.reduce((total, el) => {
        total += el.price * el.count
        return total
      }, 0) - (this.coupon.value || 0)
    }
  },
  onLoad() {
    this.buyList = uni.getStorageSync('buyList') || []
    // 根据当前时间计算日期 如果超过晚上8点 则默认选择明天 并且仅展示明天的列表
    const hour = dayjs().hour()
    if (hour >= 20) {
      this.activeDay = dayjs().add(1, 'day').format('YYYY-MM-DD')
      this.dayList = [
        {id: 0, day: `明天${dayjs().add(1, 'day').format('MM月DD日')}`, value: dayjs().add(1, 'day').format('YYYY-MM-DD')},
        {id: 1, day: `后天${dayjs().add(2, 'day').format('MM月DD日')}`, value: dayjs().add(2, 'day').format('YYYY-MM-DD')},
      ]
    } else {
      this.activeDay = dayjs().format('YYYY-MM-DD')
      this.dayList = [
        {id: 0, day: `今天${dayjs().format('MM月DD日')}`, value: dayjs().format('YYYY-MM-DD')},
        {id: 1, day: `明天${dayjs().add(1, 'day').format('MM月DD日')}`, value: dayjs().add(1, 'day').format('YYYY-MM-DD')},
        {id: 2, day: `后天${dayjs().add(2, 'day').format('MM月DD日')}`, value: dayjs().add(2, 'day').format('YYYY-MM-DD')},
      ]
    }
    this.changeDay(this.activeDay = dayjs().format('YYYY-MM-DD'))
  },
  methods: {
    deleteCount(item) {
      if (item.count === 1) {
        // 删除
        console.log(this.buyList)
        this.buyList = this.buyList ? this.buyList.filter(el => el.goods_id !== item.goods_id) : []
      } else {
        item.count--
      }
    },
    addCount(item) {
      item.count++
    },
    // 设置优惠券
    setCoupon(item) {
      console.log(item)
      const total = this.buyList.reduce((total, el) => {
        total += el.price * el.count
        return total
      }, 0)

      if (total < item.mini_value) {
        uni.showToast({
          title: '未达到优惠券使用条件',
          icon: 'none'
        })
        return false
      }
      this.coupon = item
      return true
    },
    buyAll() {
      if (!this.buyList.length) {
        uni.showToast({
          title: '请选择商品',
          icon: 'none'
        })
        return
      }
      if (this.checked) {
      } else {
        if (!this.address.id) {
          uni.showToast({
            title: '请选择地址',
            icon: 'none'
          })
          return
        }
      }

      for (let i = 0; i < this.buyList.length;i++) {
        if (!this.buyList[i].remark) {
          uni.showToast({
            title:'请填写' + this.buyList[i].tips,
            icon: 'none'
          })
          return
          break
        }
      }
      this.$api.createOrder({
        address_id: this.checked ?  undefined : this.address.id,
        member_id: uni.getStorageSync('userInfo').id,
        goods: this.buyList.map(el => {
          return {
            id: el.id,
            count: el.count,
            remark: el.remark
          }
        }),
        order_type: this.form.order_type,
        day: this.form.day,
        time: this.form.time,
        pay_type: this.form.pay_type,
        coupon_id: this.coupon.id,
        coupon_member_id: this.coupon.coupon_member_id,
        status: 1,
        remark: this.form.remark
      }).then(res => {
        uni.setStorageSync('buyList', [])
        // 将购物车商品中已购买的去除
        const carList = uni.getStorageSync('carList') || []
        const newList = carList.filter(el => {
          return !this.buyList.find(item => item.id === el.goods_id)
        })
        console.log('newList', newList)
        console.log('buyList', this.buyList)
        uni.setStorageSync('carList', newList)

        uni.redirectTo({
          url: '/pages/pay/success'
        })
      }).catch(err => {
        console.log(err)
      })
    },
    toAddress() {
      uni.navigateTo({
        url: '/pages/address/address?source=1'
      })
    },
    toGoodDetail(item) {

    },
    toDate() {
      this.dateShow = true
      this.activeDay = this.form.day
      this.activeTime = this.form.time
      this.changeDay(this.activeDay ? this.activeDay : dayjs().format('YYYY-MM-DD'))
    },
    changeDay(value) {
      this.activeDay = value
      let timeList = []
      // 如果activeDay是当天 则只能选择当前时间之后的时间 如果是后天 则可以选择所有时间
      const now = dayjs().format('YYYY-MM-DD')
      if (value === now) {
        // 当天根据当前时间计算
        const hour = dayjs().hour()
        const minute = dayjs().minute()
        let start = 8
        if (hour > 8) {
          start = hour
          if (minute > 30) {
            start++
          }
        }

        for (let i = start; i < 21; i++) {
          timeList.push(`${i}:00-${i}:30`)
          timeList.push(`${i}:30-${i+1}:00`)
        }
      } else {
        // 非当天 使用循环插入时间 早上8点到晚上8点
        for (let i = 8; i < 21; i++) {
          timeList.push(`${i}:00-${i}:30`)
          timeList.push(`${i}:30-${i+1}:00`)
        }
      }
      this.timeList = timeList
      this.activeTime = timeList[0]

    },
    confirmDate() {
      this.dateShow = false
      this.form.day = this.activeDay
      this.form.time = this.activeTime
    },
    toCoupon() {
      uni.navigateTo({
        url: '/pages/coupon/index?source=1'
      })
    }
  }
}
</script>

<style lang="scss">
.car {
  background-color: #f7f8fa;
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  padding-bottom: 120rpx;
  .date-picker-content {
    height: 500rpx;
    overflow: hidden;
    display: flex;
    background-color: rgb(242, 242, 242);
    .date-picker-slide {
      flex-shrink: 0;
      display: flex;
      flex-direction: column;
      align-items: center;
      .date-slide-item {
        font-size: 28rpx;
        color: #333333;
        padding: 13px 43px 13px 30px;
        &.active {
          background-color: #ffffff;
        }
      }
    }
    .date-time-list {
      height: 100%;
      flex-grow: 1;
      overflow: auto;
      background-color: #ffffff;
      .date-time-item {
        flex-shrink: 0;
        line-height: 80rpx;
        font-size: 28rpx;
        color: #333333;
        text-align: center;
        margin-bottom: 10px;
        &.active {
          color: #2aac34
        }
      }
    }
  }
  .handle-head {
    background-color: #FFFFFF;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    line-height: 80rpx;
    font-size: 32rpx;
    color: #dd6161;
    padding: 0 14px;
  }
  .car-list {
    overflow: auto;
    .car-item {
      position: relative;
      box-sizing: border-box;
      padding: 16rpx 32rpx;
      color: #323233;
      font-size: 24rpx;
      background-color: #FFFFFF;
      display: flex;
      .goods-detail {
        margin-left: 10px;
        flex-grow: 1;
        .goods-name {
          font-size: 28rpx;
          color: #000000;
          margin-bottom: 10px;
        }
        .goods-price-box {
          margin-top: 10px;
          display: flex;
          justify-content: space-between;
          margin-bottom: 20rpx;

          .goods-price {
            color: #2aac34;
            font-size: 28rpx;
          }
          .goods-count {
            display: flex;
            .goods-count-value{
              margin: 0 10px;
              font-size: 36rpx;
            }
          }
        }
      }
    }
  }
  .car-action {
    position: fixed;
    bottom: 0;
    left: 0;
    flex-shrink: 0;
    width: 100%;
    height: 100rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #FFFFFF;
    color: #FFFFFF;
    box-sizing: border-box;
    padding: 0 14px;
    .car-btn {

    }
    .total {
      color: #000000;
      display: flex;
      align-items: center;
    }
    .total-value {
      color: #2aac34;
      margin-right: 15px;
      font-size: 32rpx;
    }
    .total-value2 {
      color: #aeaeae;
      font-size: 24rpx;
    }
  }
  .date-picker-title {
    padding: 17px 15px;
    background-color: rgb(242, 242, 242);
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 28rpx;
    color: #333333;
    .confirm-text {
      color: #2aac34;
    }
  }
}
</style>
